package com.cs.beneficios.web.action;
import com.cs.beneficios.business.entity.BeneficiarioDAO;
import com.cs.beneficios.business.model.BeneficiarioVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.beneficios.web.form.GuardarBeneficiarioForm;
import com.cs.paoyer.administration.business.model.UserVO;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class GuardarBeneficiarioAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {

    
    ActionMessages messages = new ActionMessages();
    try
    {
      	AccessControl access = new AccessControl();
        access.validateAccess(mapping,request,response);
        
        //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
		ConnectionFactory cf = new ConnectionFactory();
    
        BeneficiarioVO objBeneVO = new BeneficiarioVO();
        GuardarBeneficiarioForm guardarForm = ( GuardarBeneficiarioForm ) form;
        HttpSession session = request.getSession();
        session.removeAttribute("CodeBeneSelected");
        
        Collection cGrupoFamiliar = null;
        Collection cBenef = null;
        
        String strDocumento = guardarForm.getNumeroDocumento();
        String strTipoDocumento = guardarForm.getTipoDocumento();
        String strOption = (String)session.getAttribute("Option");

        objBeneVO.setTipoDocumento(guardarForm.getTipoDocumento());
        objBeneVO.setNumeroDocumento(guardarForm.getNumeroDocumento());
        objBeneVO.setNombre1(guardarForm.getPrimer_nombre());
        objBeneVO.setNombre2(guardarForm.getSegundo_nombre());
        objBeneVO.setPrimerApellido(guardarForm.getPrimerApellido());
        objBeneVO.setSegundoApellido(guardarForm.getSegundoApellido());
        if(guardarForm.getDia().equalsIgnoreCase("dia") || 
          guardarForm.getMes().equalsIgnoreCase("mes") ||
          guardarForm.getAno().equalsIgnoreCase("ano") )
          {
            objBeneVO.setFechaNacimiento(null);
          }else
          {
            String strFechaNacimiento = guardarForm.getDia()+"/"+
                                    guardarForm.getMes()+"/"+
                                    guardarForm.getAno();
            objBeneVO.setFechaNacimiento(strFechaNacimiento);
          }
        
        objBeneVO.setSexo(guardarForm.getSexo());
        objBeneVO.setTelefono(guardarForm.getTelefono());
        objBeneVO.setDirDescriptiva(guardarForm.getDirDescriptiva());
        /*String dirEncasillada = guardarForm.getDirEncasillada();
        int tama = dirEncasillada.length();
        if(tama>32)
        {
          dirEncasillada = dirEncasillada.substring(0,31);
        }else
        {
          dirEncasillada+="000000000000000000000000000000";
          dirEncasillada = dirEncasillada.substring(0,31);
        }*/
        objBeneVO.setDirEncasillada(guardarForm.getDirEncasillada());
        objBeneVO.setVflComuna(guardarForm.getVflComuna());
        objBeneVO.setCobama(guardarForm.getCobama());
        objBeneVO.setCodeBarrio(guardarForm.getCodeBarrio());
        objBeneVO.setCodeZona(guardarForm.getCodeZona());
        objBeneVO.setEtnia(guardarForm.getEtnia());
        objBeneVO.setMail(guardarForm.getMail());
        //Para la auditoria de registros
        UserVO user = (UserVO) session.getAttribute("userInfo");
        String terminalAddress = request.getRemoteAddr();
        objBeneVO.setCreationUser(user.getName());
				objBeneVO.setUpdateUser(user.getName());
				objBeneVO.setCreationTerminal("WEB="+terminalAddress);
				objBeneVO.setUpdateTerminal("WEB="+terminalAddress);
        Calendar c = Calendar.getInstance(); 
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
        objBeneVO.setUpdateDate(dateFormat.format(c.getTime()));
        objBeneVO.setCreationDate(dateFormat.format(c.getTime()));
        
        String insert[] = new String[2];
        try
        {
          // Proceso para determinar si el beneficiario esta en la base de datos del SUB
          BeneficiarioDAO objBeneDAO = new BeneficiarioDAO(cf);  
          cBenef = objBeneDAO.findBeneficiarioByCriterea(objBeneVO, "ingresarBeneficiario");
          // Fin del proceso
          if(cBenef != null && cBenef.size() == 0)
          {
            insert = objBeneDAO.ingresarBeneficiario(objBeneVO); 
          }
          cf.closeConnection(objBeneDAO.getConn());
        }catch(SQLException e){
            insert[0] = "false";
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSUB - cwsub ********/");
        }
        
        if(cBenef != null && cBenef.size() == 0)
        {
          if(insert[0].equals("true"))
          {
            session.removeAttribute("beneficiarios");
            ArrayList beneList = new ArrayList();
            Collection beneficiarios=null;
            session.setAttribute("msg","");
            objBeneVO.setCode(new Long(insert[1]));
            beneList.add(objBeneVO);
            beneficiarios = beneList;
            session.setAttribute("beneficiarios",beneficiarios);
            session.setAttribute("CodeBeneSelected", insert[1]);
            if(strOption != null && !strOption.equals(""))
            {
              session.setAttribute("msgOk","El beneficiario se registro correctamente al sistema. Ahora puede asignarlo al grupo familiar");
              return mapping.findForward("VerGrupo");
            }else
            {
              cGrupoFamiliar = (Collection)session.getAttribute("InsertGrupoFamiliar");
              if(cGrupoFamiliar != null && cGrupoFamiliar.size() != 0)
              {
                return mapping.findForward("InsertGrupoFamiliar");
              }else
              {
                return mapping.findForward("success");
              }
              
              
            }
            
          }
          else
          {
            session.setAttribute("fail","No se pudo ingresar el registro..");
            return mapping.findForward("failInsert");
          }
        }else
        {
          request.setAttribute("failMsg","El beneficiario ya esta registrado en el SUB...");
          return mapping.findForward("failInsert");
        }
        
    }catch (UserException ue) 
		{
				messages.add("msgWarn",  new ActionMessage("loginForm.message."
																			+ ue.getExceptionVO().getId()));
				saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
      
    }
      
  return mapping.findForward("success");

  }
}